package work5;

import java.util.Random;

/**
 * @TODO
 * @Author xu
 * 2025/2/26
 */import java.util.Random;
import java.util.Scanner;

public class Work2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] arr = new int[10];

        System.out.println("请输入10个整数：");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = scanner.nextInt();
        }

        int index;
        while (true) {
            System.out.print("请输入一个数组索引（0-9）：");
            index = scanner.nextInt();

            if (index >= 0 && index <= 9) {
                break;
            } else {
                Random random = new Random();
                index = random.nextInt(10);
                System.out.println("输入的索引不合法，随机生成索引：" + index);
            }
        }

        System.out.println("数组中索引 " + index + " 对应的元素是: " + arr[index]);
        swapElements(arr, index);

        System.out.println("交换后的数组：");
        for (int number : arr) {
            System.out.print(number + " ");
        }
    }

    public static void swapElements(int[] arr, int index) {
        if (index > 0) {
            int temp = arr[index - 1];
            arr[index - 1] = arr[index];
            arr[index] = temp;
        }
        if (index < arr.length - 1) {
            int temp = arr[index + 1];
            arr[index + 1] = arr[index];
            arr[index] = temp;
        }
    }

}
